<template>
  <div class="markdown-body" :id="id" v-html="text"></div>
  <!--  @contextmenu="handleContextMenu($event)"-->
  <!--  <div class="node-menu" v-if="selectMenu.show" :style="{left: `${selectMenu.left}px`, top: `${selectMenu.top}px`}"
         @contextmenu="doNothing($event)">
      <div class="flex justify-content-between item"
           @click.stop="handleExec('copy_string')">
        <span>复制</span>
      </div>
      <div class="flex justify-content-between item"
           @click.stop="handleExec('add_to_note')">
        <span>加入笔记</span>
      </div>
    </div>-->
</template>
<script>
import MarkdownIt from 'markdown-it'
import mdKatex from '@traptitech/markdown-it-katex'
import mila from 'markdown-it-link-attributes'
import hljs from 'highlight.js'
import { copyString, highlightBlock, getSelection } from '@/utils/index.js'
// import { httpCreateNote } from '@/api/note.js'
// import { ElMessage } from 'element-plus'
// import useNoteStore from '@/stores/note.js'
const extendKatex = (md) => {
  md.inline.ruler.before('escape', 'math_inline', (state, silent) => {
    let match, token
    const start = state.pos
    const src = state.src
    if (src[start] === '\\' && src[start + 1] === '(') {
      match = src.slice(start).match(/\\\((.+?)\\\)/)
      if (match) {
        if (!silent) {
          token = state.push('math_inline', 'math', 0)
          token.content = match[1]
        }
        state.pos += match[0].length
        return true
      }
    }

    if (src[start] === '\\' && src[start + 1] === '\[') {
      match = src.slice(start).match(/\\\[((\n|.)+?)\\\]/)
      if (match) {
        if (!silent) {
          token = state.push('math_block', 'math', 0)
          token.content = match[1]
        }
        state.pos += match[0].length
        return true
      }
    }
    return false
  })
}

const md = new MarkdownIt({
  html: true,
  linkify: true,
  highlight(code, language) {
    const validLang = !!(language && hljs.getLanguage(language))
    if (validLang) {
      const lang = language ?? ''
      return highlightBlock(hljs.highlight(code, { language: lang }).value, lang, code)
    }
    return highlightBlock(hljs.highlightAuto(code).value, '', code)
  },
})
md.use(mila, { attrs: { target: '_blank', rel: 'noopener' } })
md.use(mdKatex, {
  blockClass: 'katexmath-block rounded-md p-[10px]',
  errorColor: ' #cc0000',
  throwOnError: false,
}).use(extendKatex)
export default {
  props: {
    value: String,
    id: String,
  },
  computed: {
    text() {
      let { value } = this
      if (!value) value = 'AI思考中...'
      // else {
      //   value = value.replace(/\\\[ |\\\[/g, '$$').replace(/ \\]|\\]/g, '$$')
      //   value = value.replace(/\\\( |\\\(/g, '$').replace(/ \\\)|\\\)/g, '$')
      // }
      return md.render(value)
    },
  },
  methods: {
    getSelectionText() {
      const selection = getSelection()
      return selection.toString().trim()
    },
    /*handleContextMenu(event) {
      event.preventDefault()
      const text = this.getSelectionText()
      if (text) {
        this.selectMenu.show = true
        this.selectMenu.left = event.clientX
        this.selectMenu.top = event.clientY
        this.selectMenu.text = text
      } else {
        this.selectMenu.show = false
      }
    },*/
    /*doNothing(event) {
      event.preventDefault()
      return false
    },
    handleExec(event) {
      switch (event) {
        case 'copy_string':
          copyString(this.selectMenu.text)
          break
        case 'add_to_note':
          const pattern = /[\s\n.,!?;:，。！？；：’‘”“'"(){}（）【】[\]《》<>\\\/\-]/g
          httpCreateNote({
            folder_id: 0,
            title: this.selectMenu.text.replace(pattern, '').substring(0, 8),
            content: this.selectMenu.text,
            icon: 'Document',
            label_id_list: [],
          }).then(() => {
            ElMessage.success('已加入笔记，请在笔记中查看和编辑')
            if (!this.noteStore) {
              this.noteStore = useNoteStore()
            }
            this.noteStore.getFolderListData()
          }).catch(() => {
          })
      }
    },*/
  },
  mounted() {
    window.copyString = copyString
    document.addEventListener('selectionchange', () => {
      if (!this.getSelectionText()) {
        this.selectMenu.show = false
      }
    })
  },
  data() {
    return {
      hljs,
      noteStore: null,
      selectMenu: {
        left: 0,
        top: 0,
        text: '',
        show: false,
      },
    }
  },
}
</script>
<style>
@import "katex/dist/katex.min.css";

.markdown-body .katex {
  font-size: 1.8em !important;
  line-height: 2.4 !important;
}
</style>
<style scoped lang="scss">
.markdown-body {
  max-width: 100%;
  overflow-x: auto;
}

.node-menu {
  background: var(--el-bg-color);
  box-shadow: var(--el-box-shadow);
  position: fixed;
  z-index: 2012;
  padding: 15px 0;
  border-radius: 6px;
  width: 150px;

  .item {
    padding: 0 15px;
    cursor: pointer;
    line-height: 2;
    font-size: 13px;
    color: var(--el-text-color-primary);

    &:hover {
      background: var(--el-bg-color-page);
    }
  }
}
</style>